package hong.jun.filter;


import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return null;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //1.获取用户信息
        RequestContext currentContext = RequestContext.getCurrentContext();

        //security上下文对象，里面有用户信息
        SecurityContext securityContext = SecurityContextHolder.getContext();

        //认证对象，里面有认证信息和授权信息
        Authentication authentication = securityContext.getAuthentication();

        //判断是不是oatuh2的认证
        if (!(authentication instanceof OAuth2Authentication)) {
            return null;
        }

        //类型状态成 OAuth2Authentication
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;

        //2.获取授权信息:
        //用户身份
        Object principal = oAuth2Authentication.getPrincipal();

        //用户认证对象：这个才是转用户信息，授权信息的对象
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();

        //用来封装权限的list
        List<String> userAuthorities = new ArrayList<>();

        //获取用户权限
        userAuthentication.getAuthorities().forEach(a -> {
            userAuthorities.add(a.getAuthority());
        });

        //3.封装成json
        //获取请求中的参数
        Map<String, String> requestParameters = oAuth2Authentication.getOAuth2Request().getRequestParameters();

        //把请求中的参数封装到map中
        Map<String, Object> jsonTokenMap = new HashMap<>(requestParameters);

        //用户名
        jsonTokenMap.put("username", userAuthentication.getName());

        //权限
        jsonTokenMap.put("userauthorities", userAuthorities);

        //4.设置到请求头转发给下游微服务
        String jsonToken = JSON.toJSONString(jsonTokenMap);

        //base64加密
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            //String encodeJsonToken = encoder.encode(jsonToken.getBytes("UTF-8"));
            currentContext.addZuulRequestHeader("json-token", jsonToken);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
